package com.tool.engine.export.write.excel;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.tool.engine.export.write.WriteTask;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ExcelWriteTask implements WriteTask {
    private List<?> data;
    private final ExcelWriter excelWriter;
    private final WriteSheet sheet;
    private final FutureTask<Boolean> futureTask = new FutureTask<>(()-> true);
    private final int size;
    private final String taskName;

    public ExcelWriteTask(List<?> data, ExcelWriter excelWriter, WriteSheet sheet, String taskName) {
        this.data = data;
        this.excelWriter = excelWriter;
        this.sheet = sheet;
        this.taskName = taskName;
        if(Objects.nonNull(data)) {
            this.size = data.size();
        }else{
            this.size = 0;
        }

    }

    @Override
    public final void write() {
        try {
            ExportTaskExcelOperation.write(data, excelWriter, sheet);
        } finally {
            futureTask.run();
            data = null;
        }
    }

    @Override
    public final boolean isSuccess() {
        try {
            return futureTask.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
           return false;
        } catch (ExecutionException e) {
            return false;
        }
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public String getTaskName() {
        return taskName;
    }
}
